package worklog.servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import worklog.db.ProjectDB;
import worklog.dto.ResponseDTO;

@WebServlet("/favProject")
public class FavoriteProject extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private ProjectDB projectDB;
	private ResponseDTO responder = new ResponseDTO();
	
    public FavoriteProject() throws Exception{ super(); }
    
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
		//doGet(request, response); 
	}

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		projectDB = new ProjectDB();
		PrintWriter out = response.getWriter();
		response.setContentType("application/json");
		if (projectDB.isReady()) out.print(processRequest(request));
		else out.print(responder.showError("DB connection error"));
		projectDB.close();
    	out.close();
	}
	
	private String processRequest(HttpServletRequest request){
		HttpSession session = request.getSession();
		if (session.getAttribute("logged") == null || (Boolean)session.getAttribute("logged") != true) return responder.showAuthError();
		int userId = (Integer) session.getAttribute("userId");

		int paramLength = request.getParameterMap().size(); 
		if (paramLength == 0) return responder.showError();
		
		String projectIdStr = request.getParameter("projectId");
		int projectId = Integer.parseInt(projectIdStr);
		if (projectDB.favoriteProject(userId, projectId)) return responder.showSuccess();
		else return responder.showError();
	}
}